//
//  HLLiveInCallLayer.m
//  YueYue
//
//  Created by hulu001 on 2024/3/12.
//

#import "HLLiveInCallLayer.h"
#import "HLZegoLiveKit.h"
#import "HLLiveInputView.h"
#import "HLLiveUserListView.h"
#import "HLUserOptionRequest.h"
#import "HLReportViewController.h"
#import "HLLiveChatView.h"
#import "HLLiveUserView.h"
#import "HLLiveHeaderUserView.h"
#import "HLGiftLiveShowCustomView.h"
#import "HLRtcRechargeView.h"
#import "HLLiveGiftContainerView.h"
#import "HLLiveGiftModel.h"
#import "HLLiveMoreView.h"
#import "HLLiveOptionRequest.h"
#import <SVGAPlayer/SVGAPlayer.h>
#import <SVGAParser.h>

@interface HLLiveInCallLayer ()<SVGAPlayerDelegate, HLLiveInputViewDelegate>
{
    BOOL _inImmersionMode;// 处于沉浸模式
}

@property (strong, nonatomic) HLLiveFemaleModel *female;
@property (strong,  nonatomic) HLLiveHeaderUserView *userHeaderView;
@property (strong,  nonatomic) QMUIButton *closeButton;
@property (strong,  nonatomic) QMUIButton *chatButton;
@property (nonatomic, strong) QMUIButton *giftBtnInCall;     // 礼物按钮
@property (nonatomic, strong) QMUIButton *moreBtnInCall;     // 更多按钮
@property (nonatomic, strong) HLLiveMoreView *moreView;
@property (strong,  nonatomic) HLLiveInputView *inputView;
@property (strong,  nonatomic) HLLiveChatView *chatView; // 视频中的聊天View
@property (strong,  nonatomic) HLLiveUserView *userView;
@property (weak,    nonatomic) HLGiftLiveShowCustomView * customGiftShow;// 礼物弹幕
@property (strong, nonatomic) SVGAPlayer *svgPlayer;

@end

@implementation HLLiveInCallLayer


- (instancetype)initWithFemale:(HLLiveFemaleModel *)female;
{
    self = [super init];
    
    if (self) {
        self.backgroundColor = UIColorClear;
        
        self.female = female;
        
        self.userView = [[HLLiveUserView alloc] init];
        [self addSubview:_userView];
        [_userView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(8);
            make.top.mas_equalTo(StatusBarHeight);
        }];
        [_userView.followButton addTarget:self action:@selector(requestFollow) forControlEvents:UIControlEventTouchUpInside];
        [_userView loadUserInfo:female];
        
        self.closeButton = [[QMUIButton alloc] init];
        [_closeButton setImage:UIImageMake(@"square_post_change_close") forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeEvent) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_closeButton];
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(40);
            make.centerY.equalTo(_userView);
            make.right.mas_equalTo(-10);
        }];
        
        self.userHeaderView = [[HLLiveHeaderUserView alloc] init];
        [self addSubview:_userHeaderView];
        [_userHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_closeButton);
            make.right.equalTo(_closeButton.mas_left).offset(-8);
            make.width.mas_equalTo(128);
        }];
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAllOnlineUsers)];
        [_userHeaderView addGestureRecognizer:tapGes];
        
        
        [self addSubview:self.chatButton];
        [self.chatButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom+12));
            make.right.mas_greaterThanOrEqualTo(-156);
        }];
        
        [self addSubview:self.inputView];
        self.inputView.hidden = YES;
        [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
        }];
        MJWeakSelf
        self.inputView.textfield.qmui_keyboardWillChangeFrameNotificationBlock = ^(QMUIKeyboardUserInfo *keyboardUserInfo) {
                [QMUIKeyboardManager handleKeyboardNotificationWithUserInfo:keyboardUserInfo showBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo) {
                    [weakSelf showToolbarViewWithKeyboardUserInfo:keyboardUserInfo];
                } hideBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo) {
                    [weakSelf hideToolbarViewWithKeyboardUserInfo:keyboardUserInfo];
                }];
            };
        
        [self addSubview:self.chatView];
        [self.chatView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 64));
            make.right.mas_equalTo(-70);
            make.height.mas_lessThanOrEqualTo(220);
        }];
        
        
        [self addSubview:self.giftBtnInCall];
        [self.giftBtnInCall mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.chatButton);
            make.right.mas_equalTo(-12);
        }];
        
        [self addSubview:self.moreBtnInCall];
        [self.moreBtnInCall mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.chatButton);
            make.right.equalTo(self.giftBtnInCall.mas_left).offset(-8);
        }];
        
        self.svgPlayer = [[SVGAPlayer alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        self.svgPlayer.loops = 1;
        self.svgPlayer.delegate = self;
        [self addSubview:self.svgPlayer];
        self.svgPlayer.hidden = YES;
        
        /*
         插入一条公告消息
         */
        HLLiveMessageExtModel *ext = [[HLLiveMessageExtModel alloc] init];
        ext.origin = @"欢迎来到直播间！严禁未成年人直播或打赏。直播间内严禁出现违法违规、低俗色情、人身伤害等，内容。请大家注意财产安全，理性消费，谨防网络诈骗。";
        HLLiveMessageModel *msg = [[HLLiveMessageModel alloc] init];
        msg.cid = @(1000);
        msg.ext = ext;
        [self.chatView addMessage:msg];
        
        [HLGCDTimerManager scheduledTimerWithName:ThumbTimeName interval:3 delaySecs:0 queue:dispatch_get_main_queue() repeats:YES action:^(NSInteger actionTimes) {
            [self refreshThumb];
        }];
        [HLGCDTimerManager start:ThumbTimeName];
        
    }
    
    return self;
}

- (void)refreshThumb
{
    [[[HLLiveOptionRequest alloc] initWithRoom:self.female.liveRoomCode type:HLLiveOptionTypeThumbCount] startWithCompletionBlockWithSuccess:^(__kindof HLLiveOptionRequest * _Nonnull request) {
        if (request.isSuccess) {
            NSString *data = [[request.result objectForKey:@"data"] stringValue];
            [self.userView.heartButton setTitle:data forState:UIControlStateNormal];
        }
    } failure:nil];
}

- (void)showAllOnlineUsers
{
    [HLLiveUserListView show];
}

- (void)refreshCurrentUsers:(NSArray <ZegoUser *>*)updateUsers type:(NSUInteger)type
{
    NSMutableArray *users = [NSMutableArray arrayWithArray:_userHeaderView.users];
    if (type == ZegoUpdateTypeAdd) {
        [users addObjectsFromArray:updateUsers];
    } else {
        NSArray *tempUsers = [NSArray arrayWithArray:users];
        for (ZegoUser *user in tempUsers) {
            for (ZegoUser *rUser in updateUsers) {
                if ([rUser.userID isEqualToString:user.userID]) {
                    [users removeObject:user];
                }
            }
        }
    }
    
    _userHeaderView.users = users;
}

- (QMUIButton *)chatButton
{
    if (!_chatButton) {
        _chatButton = [[QMUIButton alloc] init];
        _chatButton.backgroundColor = [UIColorBlack colorWithAlphaComponent:0.3];
        _chatButton.layer.cornerRadius = 16;
        _chatButton.layer.masksToBounds = YES;
        _chatButton.layer.borderColor = [UIColorWhite colorWithAlphaComponent:0.2].CGColor;
        _chatButton.layer.borderWidth = 1.6;
        _chatButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _chatButton.contentEdgeInsets = UIEdgeInsetsMake(12, 16, 12, 16);
        _chatButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_chatButton setTitle:@"说点什么…" forState:UIControlStateNormal];
        [_chatButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_chatButton addTarget:self action:@selector(chatButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chatButton;
}

- (HLLiveInputView *)inputView
{
    if (!_inputView) {
        _inputView = [[HLLiveInputView alloc] init];
        _inputView.delegate = self;
        
    }
    return _inputView;
}


- (QMUIButton *)giftBtnInCall
{
    if (!_giftBtnInCall) {
        _giftBtnInCall = [[QMUIButton alloc] init];
        [_giftBtnInCall setImage:[UIImage imageNamed:@"rtc_gift"] forState:UIControlStateNormal];
        [_giftBtnInCall addTarget:self action:@selector(giftBtnInCall:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _giftBtnInCall;
}

- (QMUIButton *)moreBtnInCall
{
    if (!_moreBtnInCall) {
        _moreBtnInCall = [[QMUIButton alloc] init];
        [_moreBtnInCall setImage:[UIImage imageNamed:@"live_in_more"] forState:UIControlStateNormal];
        [_moreBtnInCall addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtnInCall;
}

- (HLLiveMoreView *)moreView
{
    if (!_moreView){
        _moreView = [[HLLiveMoreView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210)];
    }
    
    return _moreView;
}

- (HLLiveChatView *)chatView
{
    if (!_chatView) {
        _chatView = [[HLLiveChatView alloc] init];
    }
    return _chatView;
}

- (HLGiftLiveShowCustomView *)customGiftShow{
    if (!_customGiftShow) {
        _customGiftShow = [HLGiftLiveShowCustomView addToView:self y: self.centerY-60];
        
        _customGiftShow.addMode = HLGiftLiveAddModeAdd;
        [_customGiftShow setMaxGiftCount:1];
        [_customGiftShow setShowMode:HLGiftLiveShowModeFromTopToBottom];
        [_customGiftShow setAppearModel:HLGiftLiveAppearModeLeft];
        [_customGiftShow setHiddenModel:HLGiftLiveHiddenModeLeft];
        [_customGiftShow enableInterfaceDebug:NO];
    }
    return _customGiftShow;
}

/// 关注请求
- (void)requestFollow
{
    MJWeakSelf
    [HLUIHelper followWithUserId:self.female.femaleUserId follow:NO callback:^(BOOL isConfirm) {
        if (isConfirm){
            
            [self.userView followRequest];
            
            HLLiveMessageExtModel *ext = [[HLLiveMessageExtModel alloc] init];
            ext.origin = @"关注了主播";
            HLLiveMessageModel *msg = [[HLLiveMessageModel alloc] init];
            msg.cid = @(111);
            msg.ext = ext;
            msg.fromName = HLRunTime.shareInstance.mine.nickName;
            [weakSelf.chatView addMessage:msg];
            
            NSDictionary *extObject = @{
                @"origin" :  @"关注了主播",
                @"followedNickname":HLRunTime.shareInstance.mine.nickName,
                @"followedUserId":HLRunTime.shareInstance.mine.userId,
            };
            
            NSDictionary *json = @{
                @"cid" : @(111),
                @"ext" : extObject.mj_JSONString, // 转成json字符串
            };
            // 发送
            [HLZegoLiveKit.sharedInstance sendCustomSingleControl:json.mj_JSONString];
        }
    }];
    
}

/// 充值
- (void)rechargeBtnInCall
{
    [HLRtcRechargeView show];
}

- (void)reportBtnInCall
{

    HLReportViewController *reportViewController = [[HLReportViewController alloc] initWithType:HLReportTypeMine userId:self.female.femaleUserId];
    [self.qmui_viewController.navigationController pushViewController:reportViewController animated:YES];
}

/// 礼物
- (void)giftBtnInCall:(UIButton *)button
{
    MJWeakSelf
    [HLLiveGiftContainerView showWithUser:_female callback:^(HLLiveGiftModel *gift) {
        //NSInteger duration = [info[@"userVideoDuration"] intValue];
        
        HLGiftLiveListModel *giftModel = [[HLGiftLiveListModel alloc] init];
        HLGiftLiveUserModel *userModel = [[HLGiftLiveUserModel alloc] init];
        
        NSString *giftName = gift.giftName;
        
        giftModel.name = giftName;
        giftModel.type = giftName;
        giftModel.picUrl = gift.giftUrl;
        giftModel.rewardMsg = [NSString stringWithFormat:@"%@%@",@"送", giftName];
        
        userModel.name = HLRunTime.shareInstance.mine.nickName;
        userModel.iconUrl = HLRunTime.shareInstance.mine.avatar;
        userModel.placegolderImage = [HLUIHelper avatarPlaceholder];
        HLGiftLiveShowModel *giftShowModel = [HLGiftLiveShowModel giftModel:giftModel userModel:userModel];
        [weakSelf.customGiftShow addLiveGiftShowModel:giftShowModel];
    
        HLLiveMessageExtModel *ext = [[HLLiveMessageExtModel alloc] init];
        ext.origin = [NSString stringWithFormat:@"送出一个%@",giftName];
        
        HLLiveMessageModel *msg = [[HLLiveMessageModel alloc] init];
        msg.cid = @(112);
        msg.ext = ext;
        msg.from = HLRunTime.shareInstance.mine.userId;
        msg.fromName = HLRunTime.shareInstance.mine.nickName;
        msg.messageId = [HLLiveMessageModel randomID];
        
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:gift.giftUrl] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            msg.ext.gImage = image;
            [weakSelf.chatView addMessage:msg];
        }];
        
        [weakSelf sendGiftMessage:gift];
        
    }];

}

- (void)playSVGAWithUrl:(NSString *)url
{
    MJWeakSelf;
    SVGAParser *parser = [[SVGAParser alloc] init];
    [parser parseWithURL:[NSURL URLWithString:url] completionBlock:^(SVGAVideoEntity * _Nullable videoItem) {
        if (videoItem != nil) {
            weakSelf.svgPlayer.hidden = NO;
            weakSelf.svgPlayer.videoItem = videoItem;
            [weakSelf.svgPlayer startAnimation];
        }
    } failureBlock:nil];
}
- (void)sendGiftMessage:(HLLiveGiftModel *)model
{
    /*
     发送给对方
     */
    
    if (model.giftSvgaUrl.length > 0) {
        [self playSVGAWithUrl:model.giftSvgaUrl];
    }
   
    
    NSDictionary *json = @{
        @"cid" : @(112),
        @"ext" : @{
            @"giftName" : model.giftName,
            @"giftImg" :  model.giftUrl ? : @"",
            @"giftCount": model.giftCount,
            @"giftSvga": model.giftSvgaUrl ? : @"",
            @"consumeOrderId" : model.consumeOrderId,
            @"avatar" : HLRunTime.shareInstance.mine.avatar,
        }.mj_JSONString
    };
    
    [HLZegoLiveKit.sharedInstance sendCustomSingleControl:json.mj_JSONString];
}



- (void)moreButtonAction:(UIButton *)actionButton
{
    MJWeakSelf;
    [HLLiveMoreView showWitContentView:self.moreView report:^(NSString *result) {
        [weakSelf reportBtnInCall];
    } chong:^(NSString *result) {
        [weakSelf rechargeBtnInCall];
    }];
}


- (void)chatButtonEvent:(id)sender
{
    [_inputView.textfield becomeFirstResponder];
}


- (void)showToolbarViewWithKeyboardUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo {
    if (keyboardUserInfo) {
        self.inputView.hidden = NO;
        self.chatButton.hidden = YES;
        [QMUIKeyboardManager animateWithAnimated:YES keyboardUserInfo:keyboardUserInfo animations:^{
            
            CGRect keyboardRect = IS_NOTCHED_SCREEN ? keyboardUserInfo.beginFrame : keyboardUserInfo.endFrame;
            
            CGFloat distanceFromBottom = keyboardUserInfo.isFloatingKeyboard ? 0 : [QMUIKeyboardManager distanceFromMinYToBottomInView:self keyboardRect:keyboardRect];
            
            CGFloat bottomConstant = distanceFromBottom;
            self.inputView.layer.transform = CATransform3DMakeTranslation(0, -bottomConstant, 0);
            [self.chatView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(-(bottomConstant + 48));
            }];
        } completion:NULL];
    }
}

- (void)hideToolbarViewWithKeyboardUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo {
    if (keyboardUserInfo) {
        [QMUIKeyboardManager animateWithAnimated:YES keyboardUserInfo:keyboardUserInfo animations:^{
            self.inputView.layer.transform = CATransform3DIdentity;
            [self.chatView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 64));
            }];
            self.inputView.hidden = YES;
            self.chatButton.hidden = NO;
        } completion:nil];
    }
}

- (void)liveInputView:(HLLiveInputView *)inputView willSend:(NSString *)string
{
    if (!string.length) {
        return;
    }
    
    NSString *text = string;
    // 过滤空内容
    if (text.length == 0) {
        [QMUITips showWithText:@"发送的内容为空"];
        return;
    }

    // 数字+符号
    // 不翻译 直接发送给对方
    HLUserOptionRequest *userOptionRequest = [[HLUserOptionRequest alloc] initWithType:HLUserOptionTypeTrans params:@{@"body":text}];
    [userOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLUserOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            NSString *trans = request.result[@"data"];
            [self sendMessage:trans local:text];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [self sendMessage:text local:text];
    }];
   
}

#pragma mark - 文字消息收发

- (void)sendMessage:(NSString *)text local:(NSString * _Nullable )local  {
    
    
    HLLiveMessageExtModel *ext = [[HLLiveMessageExtModel alloc] init];
    ext.origin = local;
    ext.trans = text;
    
    HLLiveMessageModel *msg = [[HLLiveMessageModel alloc] init];
    msg.cid = @(100);
    msg.ext = ext;
    msg.from = HLRunTime.shareInstance.mine.userId;
    msg.fromName = HLRunTime.shareInstance.mine.nickName;
    [self.chatView addMessage:msg];
    
    
    NSDictionary *extObject = @{
        @"origin" : local,
        @"trans" : text
    };
    
    NSDictionary *json = @{
        @"cid" : @(100),
        @"ext" : extObject.mj_JSONString, // 转成json字符串
    };
    // 发送
    [HLZegoLiveKit.sharedInstance sendCustomSingleControl:json.mj_JSONString];
    
}

- (void)addCustomCommand:(NSString *)text user:(ZegoUser *)user
{
    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                         options:0
                                                           error:nil];
    HLLiveMessageModel *msg = [HLLiveMessageModel mj_objectWithKeyValues:dict];

    if ([msg.cid integerValue] == 100) {
        msg.from = user.userID;
        msg.fromName = user.userName;
        msg.messageId = [HLLiveMessageModel randomID];
        if([_female.femaleUserId isEqualToString:user.userID]){
            msg.fromName = @"主播";
            msg.fromAvatar = _female.femaleAvatar;
        }
        [self.chatView addMessage:msg];
        
    } else if ([msg.cid integerValue] == 111) {
        msg.from = user.userID;
        msg.fromName = user.userName;
        msg.ext.origin = @"关注了主播";
        msg.messageId = [HLLiveMessageModel randomID];
        [self.chatView addMessage:msg];
    } else if ([msg.cid integerValue] == 112) {
        HLGiftLiveListModel *giftModel = [[HLGiftLiveListModel alloc] init];
        HLGiftLiveUserModel *userModel = [[HLGiftLiveUserModel alloc] init];
        
        NSString *giftName = msg.ext.giftName;

        giftModel.name = giftName;
        giftModel.type = giftName;
        giftModel.picUrl = msg.ext.giftImg;
        giftModel.rewardMsg = [NSString stringWithFormat:@"%@%@",@"送出了一个", giftName];

        userModel.name = user.userName;
        userModel.iconUrl = msg.ext.avatar;
        userModel.placegolderImage = [HLUIHelper avatarPlaceholder];
        HLGiftLiveShowModel *giftShowModel = [HLGiftLiveShowModel giftModel:giftModel userModel:userModel];
        [self.customGiftShow addLiveGiftShowModel:giftShowModel];
        
        if (msg.ext.giftSvga.length > 0) {
            [self playSVGAWithUrl:msg.ext.giftSvga];
        }
        
        msg.from = user.userID;
        msg.fromName = user.userName;
        msg.messageId = [HLLiveMessageModel randomID];
        msg.ext.origin = [NSString stringWithFormat:@"送出一个%@",giftName];;
        [self.chatView addMessage:msg];
    }
}

- (void)closeEvent
{
    if ([self.delegate respondsToSelector:@selector(onLiveClose)]) {
        [self.delegate onLiveClose];
    }
}

#pragma mark SVGAPlayerDelegate
- (void)svgaPlayerDidFinishedAnimation:(SVGAPlayer *)player
{
    self.svgPlayer.hidden = YES;
    [self.svgPlayer stopAnimation];
}

@end
